package com.example.j2eeapp.services.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.example.j2eeapp.dao.UserDao;
import com.example.j2eeapp.domain.UserEntity;
import com.example.j2eeapp.services.UserService;


/**
 * 
 * Service providing service methods to work with user data and entity.
 * 
 * @author cipherCata
 *
 */

//java does not support multiple Inheritance but as you can see it supports multiple interfaces
public class UserServiceImpl implements UserService, UserDetailsService{

	//define interface not the implementation of the interface
	private UserDao userDao;
	
	/**
	 * Create user - persist to database
	 * 
	 * @param userEntiry
	 * @return true if success
	 */
	
	//check to see if user is available by using userDao which inherent 
	//the save method from the GenericDao interface and save if available
	public boolean createUser(UserEntity userEntiry) {
		userDao.save(userEntiry);
		return true;
	}
	
	/**
	 * 
	 * Construct userDetails instance required by spring security
	 * 
	 */
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		//get user name form database/ create a var called user of type UserEntity and assign it the value of of userName
		UserEntity user = userDao.loadUserByUserName(userName);
		
		//user is null then throw exception with message.
		if (user == null){
			
			//this exception will be thrown to AuthenticationException in UserAuthenticationProviderServiceImpl class
			//which will read (No user found; Not excepted)
			throw new UsernameNotFoundException(String.format("No user found '%s'", userName));
		}
		
		//create a collection of Generic type GrantedAuthority explicitly called authorities and assign it the value of an arrayList of Generic type GrantedAuthority explicitly 
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		
		//give userDetails Authority 
		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		
		//get user info
		User userDetails = new User(user.getUserName(), user.getPassword(), authorities);
		
		return userDetails;
	}



	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	
	

}
